//
//  DXNet.m
//  suremodv
//
//  Created by dd on 13-11-30.
//  Copyright (c) 2013年 xiaomuzhi. All rights reserved.
//

#import "DXNet.h"
#import "AppDelegate.h"
#import "DXNavigationController.h"
#import "MessageService.h"
#import "SVProgressHUD.h"

@implementation DX (NET)

+ (void)reach
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 0) {
            [DX alert:@"网络访问异常，请开启网络"];
        }
    }];
}


+ (NSString *) urlEncode:(NSString *) string
{
    return  (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)string, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
}

+ (NSString *) urlDecode:(NSString *) string
{
    return [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

+ (void) validateResponse:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *data = (NSDictionary *)object;
        NSNumber *error = data[@"code"];
        
        if (error.integerValue == ERROR_TOKEN_INVALID)
        {
            DXData *dxData = [DXData sharedInstance];
            dxData.token = @"";
            dxData.user = [[NSMutableDictionary alloc] init];
            [dxData save];
            
            [[MessageService sharedInstance] stop];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOULD_LOGOUT object:nil];
            
            [SVProgressHUD showErrorWithStatus:@"您已登出"];
            
            [[AppDelegate getAppDelegate] refreshRootViewControllerWithStoryboardName:@"Login" animation:YES];
        }
    }
    

}





+ (NSString *) urlOfAction:(NSString *)action
{
    return [NSString stringWithFormat:@"%@/%@/%@", HOST, API_VERSION, action];
}

+ (NSMutableDictionary *) prepareParams
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSString *token = [[DXData sharedInstance] token];
    if (token.length > 0)
    {
        params[@"token"] = token;
    }
    params[@"client"] = CLIENT;
    params[@"version"] = [NSString stringWithFormat:@"%d", VERSION];
    return params;
}

+ (id)POST:(NSString *)action
                      parameters:(NSDictionary *)parameters
                      controller:(UIViewController *)controller
                         success:(void (^)(NSDictionary *response))success
                         failure:(void (^)(NSError *error))failure
                    failureAlert:(BOOL)failureAlert
{
    [DX reach];
    NSString *url = [DX urlOfAction:action];
    NSMutableDictionary *params = [DX prepareParams];
    [params addEntriesFromDictionary:parameters];
    
    NSString *dumpUrl = [url stringByAppendingString:@"?"];
    for (NSString *key in params.allKeys)
    {
        id value = params[key];
        dumpUrl = [dumpUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@&", key, value]];
    }
    dumpUrl = [dumpUrl stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&"]];
    [DX i:@"POST %@", dumpUrl];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    return [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [DX validateResponse:responseObject];
        // [DX i:@"%@", responseObject];
        
        if (success != nil)
        {
            if ([responseObject isKindOfClass:[NSDictionary class]])
            {
                success(responseObject);
            }
            else
            {
                if (failureAlert)
                {
                    [DX alert:NET_REQUEST_FAIL];
                }
            }
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [DX i:@"%@", operation];
        [DX i:@"%@", error];
        
        if (failure != nil)
        {
            failure(error);
        }
        else
        {
            if (failureAlert)
            {
                [DX alert:NET_REQUEST_FAIL];
            }
        }
    }];
}

+ (id)RAWPOST:(NSString *)url
parameters:(NSDictionary *)parameters
controller:(UIViewController *)controller
   success:(void (^)(id responseObject))success
   failure:(void (^)(NSError *error))failure
failureAlert:(BOOL)failureAlert
{
    NSDictionary *params = parameters;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    return [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [DX validateResponse:responseObject];
        [DX i:@"%@", responseObject];
        
        if (success != nil)
        {
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [DX i:@"%@", operation];
        [DX i:@"%@", error];
        
        if (failure != nil)
        {
            failure(error);
        }
        else
        {
            if (failureAlert)
            {
                [DX alert:NET_REQUEST_FAIL];
            }
        }
    }];
}


@end
